package genesis.familytree.server.common.code;

/**
 *
 */
class CodeMatcher {

    private String expression;

    private int start = 0;
    private int end = 0;

    public CodeMatcher(String expression) {
        this.expression = expression;
    }

    public boolean find() {
        int len = expression.length();
        int count = 0;
        boolean flag = false;
        for (int i = end; i < len; i++) {
            char c = expression.charAt(i);
            if (c == '#') {
                int nextIndex = i + 1;
                if (len > nextIndex) {
                    char next = expression.charAt(nextIndex);
                    if (next == '{') {
                        if (count != 0) {
                            throw new IllegalArgumentException("error expression: " + expression.substring(start, end));
                        }
                        start = i;
                        count = 1;
                        i = nextIndex;
                        flag = true;
                    }
                }
                continue;
            }
            if (c == '{') {
                count += 1;
                continue;
            }

            if (c == '}') {
                end = i + 1;
                if (count <= 0) {
                    continue;
                }

                count -= 1;
                if (count == 0 && flag) {

                    return true;
                }
            }
        }
        if (count != 0) {
            throw new IllegalArgumentException("错误的表达式");
        }
        return false;
    }

    public String group() {
        return expression.substring(start + 2, end - 1);
    }

    public int start() {
        return start;
    }

    public int end() {
        return end;
    }
}
